#!/bin/sh
# 1.0.0
# ./dump.sh process_name
#
if [[ $# = 0 ]]
then
    echo "You should add process_name parameter."
fi
PID=`ps -ef | grep java | grep $1 | grep -v grep | awk '{ print $2 }'`

echo $1=$PID

dump_all() {
    datetime=`date '+%m%d_%H%M%S'`

    echo $datetime
    JSTACK_FILE=${datetime}jstack.log
    JMAP_FILE=${datetime}jmap.log
    HEAP_FILE=${datetime}heap.hprof

    JSTACK_ZIP_FILE=${JSTACK_FILE}.tgz
    JMAP_ZIP_FILE=${JMAP_FILE}.tgz
    HEAP_ZIP_FILE=${HEAP_FILE}.tgz

    dump_jstack
    dump_jmap
    dump_heap
    tar_jstack
    tar_jmap
    tar_heap
}



dump_jstack() {
    echo 'dump jstack'
    jstack -l $PID > $JSTACK_FILE
    echo 'dump jstack ok'
}

dump_jmap() {
    echo 'dump jmap'
    jmap -histo $PID  > $JMAP_FILE
    echo 'dump jmap ok'
}

dump_heap() {
    echo 'dump jmap memory'
    jmap -dump:format=b,file=$HEAP_FILE $PID
    echo 'dump jmap memory ok'
}

tar_jstack() {
    echo 'tar jstack'
    tar zcvf $JSTACK_ZIP_FILE $JSTACK_FILE
    echo 'tar jstack ok'
}

tar_jmap() {
    echo 'tar jmap'
    tar zcvf $JMAP_ZIP_FILE $JMAP_FILE
    echo 'tar jmap ok'
}

tar_heap() {
    echo 'tar jmap memory'
    tar zcvf $HEAP_ZIP_FILE $HEAP_FILE
    echo 'tar jmap memory ok'
}

# main
if [[ $PID =~ ^[0-9]+$ ]]
then
    dump_all
else
    echo "PID is invalid."
fi